package org.shan.hangtian.server.handler;


import com.mlnx.common.utils.MyLog;

import org.shan.hangtian.server.session.SessionManager;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class EventHandle extends ChannelInboundHandlerAdapter {

    protected MyLog log = MyLog.getLog(getClass());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

        log.info("重新连接:{}", ctx);
        SessionManager.getInstance().refreshChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        log.info("断开连接:{}", ctx);
        SessionManager.getInstance().removehChannel(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.error("exceptionCaught", cause);

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {

                log.error("接收数据超时，移除设备");
                ctx.channel().close();
                return;
            }
        }
        super.userEventTriggered(ctx, evt);
    }



}
